<?php

namespace App\Repositories;

use App\Models\ChannelUserItem;
use App\Models\Channel;
use App\Models\Item;
use App\Models\Cooperation;
use InfyOm\Generator\Common\BaseRepository as iBaseRepository;

class ChannelUserItemRepository extends iBaseRepository
{
    /**
     * @var array
     */
    protected $fieldSearchable = [
        'channel_id',
        'wechat_user_id',
        'item_id',
        'status'
    ];

    /**
     * Configure the Model
     **/
    public function model()
    {
        return ChannelUserItem::class;
    }

    /**
     * 获取渠道用户的项目方（合作和推荐）
     */
    public function getChannelUserItems($channelId, $wechatUserId, $request)
    {
        $cooperations = Cooperation::select(['id', 'channel_id', 'item_id'])
            ->where('channel_id', $channelId)
            ->where('status', '<>', Cooperation::STATUS_DEFAULT)
            ->whereIn('item_id', function ($query) use ($request) {
                $item = new Item();
                $query->select('id')
                    ->from($item->table)
                    ->where('country', $request['country'])
                    ->get();
            })
            ->with('hasItem')
            ->simplePaginate($request['limit'] ?? 20);

        $items = ['cooperation_items' => [], 'recommend_items' => []];
        if ($cooperations->items())
        {
            foreach ($cooperations as $key => $val)
            {
                $cooperations[$key]->hasItem->logo = fileUrl($val->hasItem->logo);
            }

            $cooperations = $cooperations->toArray();
            $items['cooperation_items'] = array_column($cooperations['data'], 'has_item');
        }
        else
        {
            $items['recommend_items'] = Item::where('country', $request['country'])->orderBy('id', 'desc')->get();
        }

        return $items;
    }
}
